package com.voicechat.firstmet.client;

import android.content.Context;
import android.text.TextUtils;
import android.util.Log;

import com.alibaba.sdk.android.oss.ClientException;
import com.alibaba.sdk.android.oss.OSS;
import com.alibaba.sdk.android.oss.OSSClient;
import com.alibaba.sdk.android.oss.ServiceException;
import com.alibaba.sdk.android.oss.callback.OSSCompletedCallback;
import com.alibaba.sdk.android.oss.callback.OSSProgressCallback;
import com.alibaba.sdk.android.oss.common.auth.OSSCredentialProvider;
import com.alibaba.sdk.android.oss.common.auth.OSSPlainTextAKSKCredentialProvider;
import com.alibaba.sdk.android.oss.internal.OSSAsyncTask;
import com.alibaba.sdk.android.oss.model.GetObjectRequest;
import com.alibaba.sdk.android.oss.model.GetObjectResult;
import com.alibaba.sdk.android.oss.model.OSSRequest;
import com.alibaba.sdk.android.oss.model.PutObjectRequest;
import com.alibaba.sdk.android.oss.model.PutObjectResult;
import com.voicechat.firstmet.utils.Utils;

import java.io.File;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * @ProjectName: FirstMet
 * @Package: com.voicechat.firstmet.client
 * @ClassName: OssClient
 * @Description: oss文件上传，下载
 * @Author: ljp
 * @CreateDate: 2018/9/25 11:50
 * @Version: 1.0
 */
public class OssClient {
    private OSS oss;
    OSSAsyncTask task;
    private static String TAG = "OssClient";
    private String endpoint;
    private String bucketName;
    private String accessKeyId;
    private String accessKeySecret;

    public static OssClient getInstance() {
        return OssInstance.instance;
    }

    private static class OssInstance {
        private static final OssClient instance = new OssClient();
    }
    /**
     * 初始化
     **/
    public OssClient init(Context context) {
        this.endpoint = OssConfig.ENDPOINT;
        this.bucketName = OssConfig.BUCKET;
        this.accessKeyId = OssConfig.ACCESSID;
        this.accessKeySecret = OssConfig.ACCESSKEY;
        if (oss == null) {
            OSSCredentialProvider credentialProvider = new OSSPlainTextAKSKCredentialProvider(accessKeyId, accessKeySecret);
            oss = new OSSClient(context, endpoint, credentialProvider);
        }
        return OssInstance.instance;
    }

    /**
     * @return
     * @method
     * @description 普通文件上传
     * @date: 2018/9/25 14:14
     * @author: ljp
     */
    public void upload(String name, String filePath, String objectKey, OnUploadFile onUploadFile) {
        Log.d("name", name + ":" + filePath);
        File file = new File(filePath);
        // 文件后缀
        String fileSuffix = "";
        if (file.isFile()) {
            // 获取文件后缀名
            fileSuffix = file.getName().substring(file.getName().lastIndexOf("."));
        }
        String objectName = objectKey + "/" + name + fileSuffix;
        Log.i(TAG, "upload: -----" + objectName);
        // 构造上传请求
        PutObjectRequest put = new PutObjectRequest(bucketName, objectName, filePath);
        // 异步上传时可以设置进度回调
        put.setProgressCallback(new OSSProgressCallback<PutObjectRequest>() {
            @Override
            public void onProgress(PutObjectRequest request, long currentSize, long totalSize) {
                // Log.d("PutObject", "currentSize: " + currentSize + " totalSize: " + totalSize);
            }
        });
        task = oss.asyncPutObject(put, new OSSCompletedCallback<PutObjectRequest, PutObjectResult>() {
            @Override
            public void onSuccess(PutObjectRequest request, PutObjectResult result) {
                Log.d(TAG, "onSuccess: --------objectName-------" + oss.presignPublicObjectURL(bucketName, objectName));
                onUploadFile.onUploadFileSuccess(oss.presignPublicObjectURL(bucketName, objectName));
            }
            @Override
            public void onFailure(PutObjectRequest request, ClientException clientExcepion, ServiceException serviceException) {
                // 请求异常
                if (clientExcepion != null) {
                    // 本地异常如网络异常等
                    clientExcepion.printStackTrace();
                }
                if (serviceException != null) {
                    // 服务异常
                    Log.e("ErrorCode", serviceException.getErrorCode());
                    Log.e("RequestId", serviceException.getRequestId());
                    Log.e("HostId", serviceException.getHostId());
                    Log.e("RawMessage", serviceException.getRawMessage());
                }
            }
        });
        // task.cancel(); // 可以取消任务

        // task.waitUntilFinished(); // 可以等待直到任务完成
    }
    /**
     * 阿里云OSS上传（默认是异步多文件上传）
     *
     * @param urls
     */
    public void ossUploads(final List<String> urls,OnUploadFile onUploadFile,StringBuffer sb) throws ClientException, ServiceException {
        List<String> pictureLists = new ArrayList<>();//存放图片地址
        //判断文件是否存在
        //  boolean isExist = oss.doesObjectExist(bucketName, objectKey);
        Log.i(TAG, "onSuccess: ----"+urls.size());
        if (urls.size() <= 0) {
            // 文件全部上传完毕，这里编写上传结束的逻辑，如果要在主线程操作，最好用Handler或runOnUiThead做对应逻辑
            //onUploadFile.onUploadFileSuccess(oss.presignPublicObjectURL(bucketName, objectKey));
            return;// 这个return必须有，否则下面报越界异常，原因自己思考下哈
        }
        final String url = urls.get(0);
        if (TextUtils.isEmpty(url)) {
            urls.remove(0);
            // url为空就没必要上传了，这里做的是跳过它继续上传的逻辑。
            ossUploads(urls,onUploadFile,sb);
            return;
        }
        File file = new File(url);
        if (null == file || !file.exists()) {
            urls.remove(0);
            // 文件为空或不存在就没必要上传了，这里做的是跳过它继续上传的逻辑。
            ossUploads(urls,onUploadFile,sb);
            return;
        }
        // 文件后缀
        String fileSuffix = "";
        if (file.isFile()) {
            // 获取文件后缀名
            fileSuffix = file.getName().substring(file.getName().lastIndexOf("."));
        }
        // 文件标识符objectKey
        final String objectKey = OssConfig.ALBUM+"/" + System.currentTimeMillis() + fileSuffix;
        // 下面3个参数依次为bucket名，ObjectKey名，上传文件路径
        PutObjectRequest put = new PutObjectRequest(bucketName, objectKey, url);
        // 设置进度回调
        put.setProgressCallback(new OSSProgressCallback<PutObjectRequest>() {
            @Override
            public void onProgress(PutObjectRequest request, long currentSize, long totalSize) {
                // 进度逻辑
            }
        });
        // 异步上传
        task = oss.asyncPutObject(put,
                new OSSCompletedCallback<PutObjectRequest, PutObjectResult>() {
                    @Override
                    public void onSuccess(PutObjectRequest request, PutObjectResult result) { // 上传成功
                        urls.remove(0);
                        pictureLists.add(Utils.spitString(oss.presignPublicObjectURL(bucketName, objectKey)));
                        sb.append(Utils.spitString(oss.presignPublicObjectURL(bucketName, objectKey))+",");
                        //Log.i(TAG, "onSuccess: ----"+oss.presignPublicObjectURL(bucketName, objectKey));
                        //Log.i(TAG, "onSuccess: ----"+sb.toString());
                        if(urls.size() == 0){//是最后一张照片
                            //onUploadFile.onUploadFileSuccess(pictureLists);
                            sb.deleteCharAt(sb.length()-1);
                            onUploadFile.onUploadFileSuccess(sb.toString());
                        }
                        try {
                            ossUploads(urls,onUploadFile,sb);// 递归同步效果
                        } catch (ClientException e) {
                            e.printStackTrace();
                        } catch (ServiceException e) {
                            e.printStackTrace();
                        }
                    }
                    @Override
                    public void onFailure(PutObjectRequest request, ClientException clientExcepion,
                                          ServiceException serviceException) { // 上传失败
                        // 请求异常
                        if (clientExcepion != null) {
                            // 本地异常如网络异常等
                            clientExcepion.printStackTrace();
                        }
                        if (serviceException != null) {
                            // 服务异常
                            Log.e("ErrorCode", serviceException.getErrorCode());
                            Log.e("RequestId", serviceException.getRequestId());
                            Log.e("HostId", serviceException.getHostId());
                            Log.e("RawMessage", serviceException.getRawMessage());
                        }
                    }
                });
        // task.cancel(); // 可以取消任务
        // task.waitUntilFinished(); // 可以等待直到任务完成
    }


    /**
     * @return
     * @method
     * @description 文件下载
     * @date: 2018/9/25 16:34
     * @author: ljp
     */
    public void fileDownload(String objectKey,OnDownloadFile onDownloadFile) {
        final long get_start = System.currentTimeMillis();
        if ((objectKey == null) || objectKey.equals("")) {
            Log.w("AsyncGetImage", "ObjectNull");
        }
        GetObjectRequest get = new GetObjectRequest(bucketName, objectKey);
        get.setCRC64(OSSRequest.CRC64Config.YES);
        get.setProgressListener(new OSSProgressCallback<GetObjectRequest>() {
            @Override
            public void onProgress(GetObjectRequest request, long currentSize, long totalSize) {
                //Log.d("GetObject", "currentSize: " + currentSize + " totalSize: " + totalSize);
                int progress = (int) (100 * currentSize / totalSize);
               // mDisplayer.updateProgress(progress);
               // mDisplayer.displayInfo("下载进度: " + String.valueOf(progress) + "%");
                onDownloadFile.onDownFileProgress(String.valueOf(progress));
            }
        });
        task = oss.asyncGetObject(get, new OSSCompletedCallback<GetObjectRequest, GetObjectResult>() {
            @Override
            public void onSuccess(GetObjectRequest request, GetObjectResult result) {
                // 请求成功
                InputStream inputStream = result.getObjectContent();
                onDownloadFile.onDownFileSuccess(inputStream);
            }
            @Override
            public void onFailure(GetObjectRequest request, ClientException clientExcepion, ServiceException serviceException) {
                String info = "";
                // 请求异常
                if (clientExcepion != null) {
                    // 本地异常如网络异常等
                    clientExcepion.printStackTrace();
                    info = clientExcepion.toString();
                }
                if (serviceException != null) {
                    // 服务异常
                    Log.e("ErrorCode", serviceException.getErrorCode());
                    Log.e("RequestId", serviceException.getRequestId());
                    Log.e("HostId", serviceException.getHostId());
                    Log.e("RawMessage", serviceException.getRawMessage());
                    info = serviceException.toString();
                }
              ///  mDisplayer.downloadFail(info);
               // mDisplayer.displayInfo(info);
            }
        });
    }


    public interface OnUploadFile {
        void onUploadFileSuccess(String info);
       // void onUploadFileSuccess(List<String> pictures);
        void onUploadFileFailed(String errCode);
    }

    public interface OnDownloadFile {
        void onDownFileSuccess(InputStream inputStream);
        void onDownFileProgress(String progress);
    }



}


